import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Space,
  Card,
  Row,
  Col,
  Tag,
  Collapse,
  Typography
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  SearchOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { getDictionaryApi, addDictionaryApi, updateDictionaryApi, getDictionaryTypesApi, getDictionaryByTypeApi, toggleDictionaryStatusApi } from '../../api/dictionaryApi';

const { Option } = Select;
const { Panel } = Collapse;
const { Text } = Typography;

const DictionaryManagement = () => {
  const [form] = Form.useForm();
  const [dictForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dictTypes, setDictTypes] = useState([]);
  const [dictDataMap, setDictDataMap] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingDict, setEditingDict] = useState(null);
  const [selectedDictType, setSelectedDictType] = useState(null);
  // 获取字典类型列表
  const fetchDictTypes = async () => {
    setLoading(true);
    try {
      const response = await getDictionaryTypesApi({});
      if (response.code === '0' || response.code === 200) {
        setDictTypes(response.data || []);
      } else {
        message.error('获取字典类型失败');
      }
    } catch (error) {
      message.error('获取字典类型失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取指定字典类型的数据（包含所有状态）
  const fetchDictDataByType = async (dictType) => {
    try {
      const response = await getDictionaryByTypeApi({ dictType });
      if (response.code === '0' || response.code === 200) {
        setDictDataMap(prev => ({
          ...prev,
          [dictType]: response.data || []
        }));
      } else {
        message.error('获取字典数据失败');
      }
    } catch (error) {
      message.error('获取字典数据失败');
    }
  };

  // 处理字典类型展开
  const handleDictTypeExpand = (dictType) => {
    if (!dictDataMap[dictType]) {
      fetchDictDataByType(dictType);
    }
  };

  // 打开新增/编辑弹窗
  const handleOpenModal = (record = null, dictType = null) => {
    setEditingDict(record);
    setSelectedDictType(dictType);
    if (record) {
      dictForm.setFieldsValue(record);
    } else {
      dictForm.resetFields();
      if (dictType) {
        dictForm.setFieldsValue({ dictType });
      }
    }
    setModalVisible(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingDict(null);
    setSelectedDictType(null);
    dictForm.resetFields();
  };

  // 提交表单
  const handleSubmit = async (values) => {
    try {
      let response;
      if (editingDict) {
        response = await updateDictionaryApi({ ...values, id: editingDict.id });
      } else {
        response = await addDictionaryApi({ ...values, status: '0' });
      }

      if (response.code === '0' || response.code === 200) {
        message.success(editingDict ? '更新成功' : '新增成功');
        handleCloseModal();
        // 刷新对应字典类型的数据
        if (values.dictType) {
          fetchDictDataByType(values.dictType);
        }
      } else {
        message.error(response.msg || '操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 停用/启用字典
  const handleToggleStatus = async (record) => {
    try {
      const response = await toggleDictionaryStatusApi({
        id: record.id,
        status: record.status
      });
      if (response.code === '0' || response.code === 200) {
        message.success(response.msg || '操作成功');
        // 刷新对应字典类型的数据
        if (record.dictType) {
          fetchDictDataByType(record.dictType);
        }
      } else {
        message.error(response.msg || '操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    fetchDictTypes();
  }, []);

  // 字典数据表格列定义
  const dictDataColumns = [
    {
      title: '字典标签',
      dataIndex: 'dictLabel',
      key: 'dictLabel',
      width: 150,
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
      key: 'dictValue',
      width: 150,
    },
    {
      title: '排序',
      dataIndex: 'dictSort',
      key: 'dictSort',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === '0' ? 'green' : 'red'}>
          {status === '0' ? '正常' : '停用'}
        </Tag>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      headerAlign: 'center',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleOpenModal(record, record.dictType)}
          >
            编辑
          </Button>
          <Popconfirm
            title={`确定要${record.status === '0' ? '停用' : '启用'}这个字典项吗？`}
            onConfirm={() => handleToggleStatus(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger={record.status === '0'}
              style={{ color: record.status === '1' ? '#52c41a' : undefined }}
            >
              {record.status === '0' ? '停用' : '启用'}
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card title="字典管理">
        <Collapse
          onChange={(activeKeys) => {
            if (activeKeys.length > 0) {
              const dictType = activeKeys[activeKeys.length - 1];
              handleDictTypeExpand(dictType);
            }
          }}
        >
          {dictTypes.map((dictType) => (
            <Panel
              key={dictType.dictType}
              header={
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <Text strong>{dictType.dictName}</Text>
                    <Text type="secondary" style={{ marginLeft: 8 }}>
                      ({dictType.dictType})
                    </Text>
                  </div>
                  <div>
                    <Button
                      type="link"
                      icon={<PlusOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleOpenModal(null, dictType.dictType);
                      }}
                    >
                      新增
                    </Button>
                  </div>
                </div>
              }
            >
              <Table
                columns={dictDataColumns}
                dataSource={dictDataMap[dictType.dictType] || []}
                rowKey="id"
                loading={loading}
                pagination={false}
                size="small"
              />
            </Panel>
          ))}
        </Collapse>
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editingDict ? '编辑字典' : '新增字典'}
        open={modalVisible}
        onCancel={handleCloseModal}
        footer={null}
        width={600}
      >
        <Form
          form={dictForm}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="dictType"
                label="字典类型"
                rules={[{ required: true, message: '请选择字典类型' }]}
              >
                <Select 
                  placeholder="请选择字典类型" 
                  disabled={!!selectedDictType}
                >
                  {dictTypes.map(type => (
                    <Option key={type.dictType} value={type.dictType}>
                      {type.dictName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="dictSort"
                label="排序"
                rules={[{ required: true, message: '请输入排序' }]}
              >
                <Input type="number" placeholder="请输入排序" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="dictLabel"
                label="字典标签"
                rules={[{ required: true, message: '请输入字典标签' }]}
              >
                <Input placeholder="请输入字典标签" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="dictValue"
                label="字典键值"
                rules={[{ required: true, message: '请输入字典键值' }]}
              >
                <Input placeholder="请输入字典键值" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="请输入备注" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingDict ? '更新' : '新增'}
              </Button>
              <Button onClick={handleCloseModal}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DictionaryManagement;